import { message } from "antd";
import axios from "axios";
const url = import.meta.env.VITE_BASE_URL;

console.log(url, "url");

const instance = axios.create({
  baseURL: url,
  timeout: 1000 * 3,
  timeoutErrorMessage: "请求超时，请刷新页面",
  withCredentials: true,
  headers: {
    "Content-Type": "application/json",
    Authorization: "Bearer " + localStorage.getItem("token") || "",
  },
});

instance.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    const data = response.data;

    if (data?.code === 40001) {
      window.location.href = "/login";
    } else if (data?.code !== 200) {
      message.error(data?.msg || "请求出错，请稍后重试");
    }
    return data.data;
  },
  (error) => {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

export default {
  get: (url: string, params?: object) => {
    return instance.get(url, { params });
  },
  post: (url: string, params?: object) => {
    return instance.post(url, params);
  },
  put: (url: string, params?: object) => {
    return instance.put(url, params);
  },
  delete: (url: string, params?: object) => {
    return instance.delete(url, { params });
  },
};
